package com.wufun.overseas.main.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.facebook.drawee.view.SimpleDraweeView;
import com.fasterxml.jackson.databind.JavaType;
import com.wufun.baselibrary.download.CommonDownloadTask;
import com.wufun.baselibrary.impl.AdapterInterface;
import com.wufun.baselibrary.net.HttpUtils;
import com.wufun.baselibrary.utils.LogUtils;
import com.wufun.baselibrary.widgets.SwipeRefreshView;
import com.wufun.overseas.R;
import com.wufun.overseas.adapters.GameDetailAdapter;
import com.wufun.overseas.adapters.MyHomerAdapter;
import com.wufun.overseas.main.base.MyActivity;
import com.wufun.overseas.main.base.MyApplication;
import com.wufun.overseas.models.bean.GameDetailBean;
import com.wufun.overseas.models.bean.MyHomeBean;
import com.wufun.overseas.models.bean.MySearchDetailBean;
import com.wufun.overseas.models.db.DownLoadModel;
import com.wufun.overseas.rpc.RpcConstant;
import com.wufun.overseas.tools.DownloadManager;
import com.wufun.overseas.utils.JsonMapper;
import com.wufun.overseas.view.IXListViewLoadMore;
import com.wufun.overseas.view.IXListViewRefreshListener;
import com.wufun.overseas.view.XListView2;
import com.wufun.overseas.view.ptr.PtrClassicFrameLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * 游戏列表 内层进来的
 */
public class GameDetailActivity extends MyActivity implements View.OnClickListener, AdapterInterface {

    @Bind(R.id.gamede_back_ll)
    LinearLayout gamede_back_ll;
    @Bind(R.id.gamede_iv_title)
    SimpleDraweeView iv_icon;
    @Bind(R.id.gamede_tv_title)
    TextView tv_title;
    @Bind(R.id.gamede_listview)
    XListView2 listView;
    @Bind(R.id.layout_search_ll)
    LinearLayout layout_search_ll;
    @Bind(R.id.mPtrFrame_gamedetail)
    PtrClassicFrameLayout swipeRefreshView;
    private int PreIndex = 0;

    private int Btn_index;

    List<GameDetailBean.DataBean.PostListBean> data = null;
    GameDetailAdapter adapter;
    private int page = 1;
    private String imguri;
    private String title;
    private String fid; //点击首页传过来的id作为fid

    private boolean isLoading = false;
    private boolean isFirstpage = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_detail);
        ButterKnife.bind(this);
    }

    @Override
    public void initWidget(View... v) {
        super.initWidget(v);
        adapter = new GameDetailAdapter(GameDetailActivity.this, this);
        listView.setAdapter(adapter);
        data = adapter.getData();

        final Intent intent = getIntent();
        title = intent.getStringExtra("title");
        imguri = intent.getStringExtra("imguri");
        fid = intent.getStringExtra("fid");

        rootBarRl.setVisibility(View.GONE);
        tv_title.setText(title);

        getNetData();
        listView.setPullRefreshEnable(new IXListViewRefreshListener() {
            @Override
            public void onRefresh() {
                if (isLoading)
                    return;
                page = 1;
                PreIndex = 0;
                isFirstpage = true;
                getNetData();
            }
        });
        iv_icon.setImageURI(imguri);
        listView.setPullLoadEnable(new IXListViewLoadMore() {
            @Override
            public void onLoadMore() {
                if (isLoading)
                    return;
                getNetData();
            }
        });
        listView.setPreLoadCount(6);
        inits();

        layout_search_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(GameDetailActivity.this, SearchDetailActcivity.class);
                intent1.putExtra("FID", fid);
                startActivity(intent1);


            }
        });

    }

    private void inits() {
        gamede_back_ll.setOnClickListener(this);
//        ed_search.setOnClickListener(this);
//        iv_search.setOnClickListener(this);

    }

    private GameDetailBean mydt;

    public void getNetData() {
//        Log.e("TAG", page + "yy");
        isLoading = true;
        LogUtils.e(">>>>>>>>>>>>00000");
        HttpUtils.doGet(RpcConstant.forumRootUrl + "/forum/forum/getPostByType?fid=" + fid + "&page=" + (page++) + "&orderBy=1&limit=10&uid=30236975&token=vVv4U6REug8dyI5Z", new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                listView.setNoMore();
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    LogUtils.e(">>>>>>>>>>>>0000");
                    JavaType javaType = JsonMapper.getInstance().createCollectionType(GameDetailBean.class);
                    mydt = JsonMapper.getInstance().fromJson(response.body().string(), javaType);
                    if (mydt != null && mydt.getData().getPost_list().size() > 0) {
                        if (mydt.getData().getPost_list().size() < 10) {
                            Message msg = new Message();
                            msg.what = 2;
                            cwjHandler.sendMessage(msg);
                        }

                        LogUtils.e(">>>>>>>>>>>>000");
                        Message msg = new Message();
                        msg.what = 1;
                        cwjHandler.sendMessage(msg); //高速UI线程可以更新结果了
                    } else {
                        LogUtils.e(">>>>>>>>>>>>00");
                        Message msg = new Message();
                        msg.what = 2;
                        cwjHandler.sendMessage(msg);
                    }

                } catch (IOException e) {
                    LogUtils.e(">>>>>>>>>>>>0");
                    Message msg = new Message();
                    msg.what = 3;
                    cwjHandler.sendMessage(msg);
                    e.printStackTrace();
                }
            }
        });

    }

    @SuppressLint("HandlerLeak")
    final Handler cwjHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    updateUI();
                    stopLoad();
                    break;
                case 2:
                    listView.setNoMore();
                    if (adapter != null)
                        adapter.notifyDataSetChanged();
                    stopLoad();
                    break;
                case 3:
                    showToast(getResources().getString(R.string.getnetdata_error));
                    stopLoad();
                    break;
                case 4:
                    adapter.setReflash();
                    break;

            }
        }
    };

    private void stopLoad() {
        LogUtils.e(">>>>>>>>>>>>1111");
        listView.stopLoadMore();
        listView.stopRefresh();
        isLoading = false;
        LogUtils.e(">>>>>>>>>>>>2222");
    }


    private void updateUI() {
        LogUtils.e(">>>>>>>>>>>>3333");
        if (isFirstpage) {
            data.clear();
            isFirstpage = false;
        }
        if (adapter == null) {
            adapter = new GameDetailAdapter(GameDetailActivity.this, this);
            listView.setAdapter(adapter);
            data = adapter.getData();
        }
        data.addAll(mydt.getData().getPost_list());
        LogUtils.e(">>>>>>>>>>>>4444");
        adapter.notifyDataSetChanged();
        if (PreIndex == data.size() && data.size() != 0) {
            listView.setNoMore();
            return;
        }
        PreIndex = data.size();
        LogUtils.e(">>>>>>>>>>>>5555");
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.gamede_back_ll:
                finish();
                break;
//            case R.id.gamede_ed:
//
//                break;
//            case R.id.gamede_iv_search:
//
//                break;
        }
    }


    @Override
    public void onAdapterItemClick(View view, int position) {
        Btn_index = position;
        DownLoadModel start = null;
        try {
            if (data.get(position).getRelation_game().getGame_down_url_mote() != null) {
                if (data.get(position).getRelation_game().getGame_down_url_mote().indexOf("apk") != -1) {
                    Toast.makeText(GameDetailActivity.this, "URI ERROR", Toast.LENGTH_SHORT).show();
                    return;
                }
                start = DownloadManager.getInstance().getDownloadByUrl(data.get(position).getRelation_game().getGame_down_url_mote());

                if (start != null) {
                    if (start.getStatus() == CommonDownloadTask.STATUS_FINISH) {
                        StartGame(data.get(position).getRelation_game().getGame_down_url_mote(), start.getGamePath() + "/" + start.getGameZipName().replace(".zip", ""));
                    } else if (start.getStatus() == CommonDownloadTask.STATUS_STOP) {
                        download(start);
                    } else if (start.getStatus() == CommonDownloadTask.STATUS_PROGRESS) {
                        if (factory.isExitTask(start.getDownloadUrl()))
                            factory.cancelTask(start.getDownloadUrl());
                        else {
                            download(start);
                        }
                    } else {
                        download(start);
                    }
                } else {
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < data.get(position).getRelation_game().getGame_tag_info().size(); i++) {
                        if (i < (data.get(position).getRelation_game().getGame_tag_info().size() - 1)) {
                            sb.append(data.get(position).getRelation_game().getGame_tag_info().get(i).getId() + ",");
                        } else {
                            sb.append(data.get(position).getRelation_game().getGame_tag_info().get(i).getId());
                        }
                    }
                    addDownloadToDB(data.get(position).getRelation_game().getGame_name(),
                            data.get(position).getRelation_game().getGame_down_url_mote(),
                            data.get(position).getRelation_game().getGame_id(),
                            data.get(position).getRelation_game().getGame_ico_remote(),
                            data.get(position).getRelation_game().getGame_size(),
                            sb.toString());
                    Intent intent = new Intent(GameDetailActivity.this, DownloadManagerActivity.class);
                    intent.putExtra("title", "Download Management");
                    startActivity(intent);
                }
            } else {
                Toast.makeText(GameDetailActivity.this, "URI ERROR", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(GameDetailActivity.this, "URI ERROR", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

    }

    private void download(DownLoadModel start) {
        try {
            factory.addTask(new CommonDownloadTask(start.getDownloadUrl()
                    , start.getGameZipName()
                    , start.getDownloadDir()
                    , start.getGameName()));
        } catch (Exception e) {
            showToast(e.getMessage());
        }
    }

    @Override
    public void onDownloadStop(String url, String gamename) {
        super.onDownloadStop(url, gamename);
        Message msg = new Message();
        msg.what = 4;
        cwjHandler.sendMessage(msg);
    }

    @Override
    public void onDownloadZIPError(String url, String gameName) {
        super.onDownloadZIPError(url, gameName);
        Message msg = new Message();
        msg.what = 4;
        cwjHandler.sendMessage(msg);
    }

    @Override
    public void onDownloadZIPProgress(String url, int progress, String speed) {
        super.onDownloadZIPProgress(url, progress, speed);
        Message msg = new Message();
        msg.what = 4;
        cwjHandler.sendMessage(msg);
    }

    @Override
    public void onDownloadStarZIP(String url, String gameName) {
        super.onDownloadStarZIP(url, gameName);
        Message msg = new Message();
        msg.what = 4;
        cwjHandler.sendMessage(msg);
    }

    @Override
    public void onDownloadFinish(String url, String gameName) {
        super.onDownloadFinish(url, gameName);
        Message msg = new Message();
        msg.what = 4;
        cwjHandler.sendMessage(msg);
    }

    @Override
    public void onDownloadStart(String url, String gameName) {
        super.onDownloadStart(url, gameName);
        Message msg = new Message();
        msg.what = 4;
        cwjHandler.sendMessage(msg);
    }

    @Override
    public void onDownloadError(String url, String gameName) {
        super.onDownloadError(url, gameName);
        Message msg = new Message();
        msg.what = 4;
        cwjHandler.sendMessage(msg);
    }

    @Override
    public void onDownloadProgress(String url, int progress, String speed) {
        super.onDownloadProgress(url, progress, speed);
        adapter.getSpeed(progress, speed);
        Message msg = new Message();
        msg.what = 4;
        cwjHandler.sendMessage(msg);
    }
}
